<?php

namespace app\api\controller;

use AlibabaCloud\AmqpOpen\V20191212\DeleteBinding;
use app\admin\model\DoMember;
use app\admin\model\Expert;
use app\admin\model\Projectcategory;
use app\admin\model\ProjectHave;
use app\admin\model\Projectjoin;
use app\admin\model\Projectkefu;
use app\admin\model\Projects;
use app\admin\model\Projectuser;
use app\admin\model\shopro\Goods;
use app\admin\model\Shoprogoods;
use app\admin\model\Vip;
use app\admin\model\Viptype;
use app\admin\model\yalimedia\Teacher;
use app\common\controller\Api;
use app\common\model\ScoreLog;
use app\common\model\User;
use Cassandra\Uuid;
use think\Db;

class Project extends Api
{
    //如果$noNeedLogin为空表示所有接口都需要登录才能请求
    //如果$noNeedRight为空表示所有接口都需要验证权限才能请求
    //如果接口已经设置无需登录,那也就无需鉴权了
    //
    // 无需登录的接口,*表示全部
    protected $noNeedLogin = ['getCategory', 'list', 'getConfig', 'info','suggest','memdesc','kefu'];
    // 无需鉴权的接口,*表示全部
    protected $noNeedRight = "*";

    public function suggest()
    {
        $map = [
            'status' => 1,
            'is_hot' => 1,
        ];
        $list = Projects::where($map)->limit(6)->select();
        foreach ($list as &$v){
            $v['image'] = cdnurl($v['image'],true);
            $is_fav = 0;
            if($this->auth->isLogin()){
                $map = [
                    'user_id' => $this->auth->id,
                    'project_id' => $v['id'],
                ];
                $c = Db::table('fa_project_fav')->where($map)->find();
                $is_fav = $c?1:0;
            }

            $v['is_fav'] = $is_fav; //0=未收藏 1=收藏
        }

        $this->success('成功',$list);
    }

    public function haveProject()
    {
        if(empty(input('project_name'))){
            $this->error('project_name必传');
        }
      /*  if(empty(input('file'))){
            $this->error('project_name必传');
        }*/
        $user = $this->auth->getUser();
       /* $map = [
            'user_id' => $user['id'],
            'status'=> 0,
        ];
        $row = Projectuser::where($map)->find();
        if($row){
            $this->error('已提交，请等待客服联系');
        }*/
        $input = input();
        $data['user_id'] = $user['id'];
        $data['project_name'] = $input['project_name'];
        $data['project_desc'] = $input['project_desc'];
        $data['file'] = $input['file'];
        $model = new Projectuser($data);
        $model->allowField(true)->save();
        $this->success('成功');
    }

    public function getConfig()
    {
        $this->success(null, config('site.' . request()->get('config')));
    }

    public function getCategory()
    {
        $pid = input('pid',0);
        if($pid > 0){
            $category = new Projectcategory();
            $list = $category->order('weigh desc')
                ->where('pid', $pid)
                ->select();
            $list = collection($list)->toArray();
            $arr = [
                'id' => $pid,
                'image' => '',
                'pid' => '',
                'type_name' => '全部',
            ];
            array_unshift($list,$arr);
        }else{
            $category = new Projectcategory();
            $list = $category->order('weigh desc')
                ->where('pid', $pid)
                ->select();
            $list = collection($list)->toArray();
        }

        foreach ($list as &$v){
            $v['image'] = cdnurl($v['image'],true);
        }
        $this->success(null, $list);
    }



    public function list()
    {
        $project = new \app\admin\model\Project();
        $limit = request()->get('limit', 10);
        $map = ['status' => 1];
        if(input('search')){
            $map['project_name'] = ['like','%'.input('search').'%',];
        }
        if((int)input('category')){
            $mlist = Db::table('fa_project_category')->where('pid',input('category'))->select();
            if($mlist){
                $map['project_type'] = ['in',array_column($mlist,'id')];
            }else{
                $map['project_type'] = (int)input('category');
            }
        }

        /*if(area_id()){
            $map['area_id'] = ['in',area_id()];
        }*/
        if(area_ids()){
            $project->where(area_ids());
        }
        $list = $project->where($map)->order('createtime', 'desc')
                ->paginate($limit)
                ->toArray();
        if(area_ids()){
        }else{
            if(empty($list)){
                $list = $project->where('')->order('createtime', 'desc')
                    ->paginate($limit)
                    ->toArray();
            }
        }
        foreach ($list['data'] as &$v){
            $v['image'] = cdnurl($v['image'],true);
            $is_fav = 0;
            if($this->auth->isLogin()){
                $map = [
                    'user_id' => $this->auth->id,
                    'project_id' => $v['id'],
                ];
                $c = Db::table('fa_project_fav')->where($map)->find();
                $is_fav = $c?1:0;
            }
            $v['is_fav'] = $is_fav; //0=未收藏 1=收藏
            $v['project_desc'] = strip_tags($v['project_desc']);
        }
        $this->success(null, $list);
    }

    public function info()
    {
        $id = input('id');

        $project = new \app\admin\model\Project();

        $info = $project->where('id', $id)->find();
        if(empty($info)){
            $this->error('参数错误');
        }
        $info = $info->toArray();
        $info['file'] = cdnurl($info['file'],true);
        $is_join = 0;
        if($this->auth->isLogin()){
            $where = [
                'user_id' => $this->auth->id,
                'project_id' => $id,
            ];
            $j = Projectjoin::where($where)->find();
            $is_join = $j?1:0;
        }
        $info['is_join'] = $is_join;
        $res = file_get_contents('https://apis.map.qq.com/ws/geocoder/v1/?address='.$info['address'].'&key=34GBZ-ZG66D-KV54R-P3DBA-L5F6O-QQFOT');
        $info['location'] = [];
        $res = json_decode($res,true);

        if($res['message'] == 'Success'){
            if(!empty($res['result']['location'])){
                $info['location'] = $res['result']['location'];
            }
        }
      

        $expert_list = Expert::where('id','in',explode(',',$info['expert_id']))->select();
        $expert_list = collection($expert_list)->toArray();
        foreach($expert_list as &$vv){
            $vv['image'] = cdnurl($vv['image'],true);
        }
        $info['expert_list'] = $expert_list;
        $expert_id = 0;
        if($expert_list){
            $expert_id = $expert_list[0]['id'];
        }
        $expert = Expert::where('id',$expert_id)->find();
        $expert['image'] = cdnurl($expert['image'],true);
        $info['expert'] = $expert;
        $info['is_two'] = count($expert_list)>1?1:0;
        $goodsList = Shoprogoods::where('id','in',explode(',',$info['goods_ids']))
            ->field('id,title,subtitle,image')
            ->select();
        foreach ($goodsList as &$v){
            $v['image'] = cdnurl($v['image'],true);
        }
        $info['goodslist'] = $goodsList;
        $kefuList = Projectkefu::where('id','in',explode(',',$info['kefu_ids']))
            ->select();
        foreach ($kefuList as &$v){
            $v['image'] = cdnurl($v['image'],true);
            $v['qrimage'] = cdnurl($v['qrimage'],true);
        }
        $info['kefu'] = $kefuList;
        $this->success(null, $info);
    }

    public function vipprice()
    {
        $vip = Vip::where("")->find();
        $this->success('成功', $vip);
    }

    public function expert2()
    {
        $expert = Expert::where('id',input('id'))->find();
        if(!$expert){
            $this->error('参数错误');
        }
        $expert['image'] = cdnurl($expert['image'],true);
        $this->success(null, $expert);
    }

    //我要参与
    public function viplist()
    {
        $list = Viptype::all();
        foreach($list as &$v){
            $v['viplist'] = Vip::where('type_id',$v['id'])->select();
        }
        $this->success('成功',$list);
    }

    public function joinProject()
    {
        $data = request()->post();
        $user = $this->auth->getUser();
        if($user['level'] <=0){
            $this->error('请先加入会员');
        }
        if (!isset($data['join_type']))
            $this->error("参与类型不能为空");
        $project = \app\admin\model\Project::get(input('project_id'));
        if(!$project){
            $this->error("项目错误");
        }

        //print_r($data);die();
        $map = [
            'user_id' => $this->auth->id,
            'project_id' => input('project_id')
        ];
        $pro = Projectjoin::where($map)->find();
        if($pro){
            $this->error("您已加入");
        }
        $projectJoin = new Projectjoin();

        $data['user_id'] = $this->auth->id;
        $data['projecttype_ids'] = input('join_type');
        $projectJoin->allowField(true)->save($data);

        $this->success("提交成功");
    }
    public function memdesc()
    {
        $data = [
            'title1'=> '成功成为经纪人后，平台代表将联系您，请注意接听1661666777或16566665656来电',
            'title1'=> config('site.jingji_phone'),
            'title2'=> '该老师在当地收益的40%6将奖励给当地经纪人。另外付款页面也同时显示信息收集框',
            'title2'=>  config('site.jingji_quanyi'),
        ];
        $this->success("提交成功",$data);
    }

    public function kefu()
    {
        $list = Projectkefu::where('state',1)->where('is_set',1)->limit(4)->select();
        foreach ($list as &$v){
            $v['image'] = cdnurl($v['image'],true);
            $v['qrimage'] = cdnurl($v['qrimage'],true);
        }
        $this->success("提交成功",$list);
    }


    public function doMember()
    {
        if (!request()->isPost()){
            $this->error("请求方式有误");
        }
        $data = request()->post();

      /* $vip = Vip::get(input('vip_id'));
       if(empty($vip)){
           $this->error('请选择会员');
       }*/

        $user = $this->auth->getUser();

        $data['user_id'] = $user['id'];
        if(isset($data['teacher_id'])){

            $map = [
                'teacher_id'=>$data['teacher_id'],
                'status'=>1,
                'user_id'=>$user['id'],
            ];
            $do = DoMember::where($map)->find();
            if($do){
                $this->error('您已开通经纪人');
            }
            $t = Teacher::get($data['teacher_id']);
            if(empty($t)){
                $this->error('讲师参数错误');
            }
            $price = $t['price'];
            $title = '成为经纪人';
        }else{
            if ($user['level'] > 0){
                $this->error("您已经是会员");
            }
            $v = Vip::where("")->find();
            $price = $v['price'];
            $title = '会员支付';
        }
        $data['file'] = isset($data['file_path'])?$data['file_path']:'';
        $orderid = create_sn('N');
        $data['orderid'] = $orderid;
        $doMember = new DoMember($data);

        if ($data['pay_type'] == 1) { // 微信支付
            $doMember->allowField(true)->save();
            $auth = Db::table('fa_shopro_user_oauth')->where("user_id",$this->auth->id)->find();
            if(!$auth){
                $this->error('未授权用户');
            }
            $params = [
                'amount' =>$price,
                'orderid' => $orderid,
                'type' => "wechat",
                'title' => $title,
                'notifyurl' => request()->domain()."/addons/epay/api/notifyx/type/wechat",
                'returnurl' => "返回地址",
                'method' => "mini",
                'openid' => "ocvDX5TRuNS8pP1v5wTm8mEJ7tN4",
                'openid' => $auth['openid'],
            ];
            $data=[
                'is_pay' => 0,
                'data' => \addons\epay\library\Service::submitOrder($params),
            ];
            $this->success('成功', $data);
        } else if ($data['pay_type'] == 2) { // 积分支付

            if ($user['score'] < $vip['score'])
                $this->error("剩余积分不足以支付");
            $data['status'] = 1;
            $doMember->save($data);
            ScoreLog::scoreDesc($this->auth->id,$vip['score'],'购买'.$vip['name']);

            $user = User::get($this->auth->id);
            $user->level = $vip['id'];
            if(input('pay_type') == 2){
                $user->jingji_area = input('city_area','');
                $user->is_jingji = 1;
            }
            $user->save();

            $data=[
                'is_pay' => 1,
                'data' => [],
            ];
            $this->success('成功', $data);
        } else{
            $this->error("支付方式有误");
        }

        $this->success("ok");
    }

}